package com.zw.a.basic.a14.demo08_tcp_exercise;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

//案例: 客户端给服务器端上传文件.
//自定义的服务器端, 用来接收客户端传过来的数据, 并将其写入到目的地文件中.
public class ServerDemo {
    public static void main(String[] args) throws IOException {
        //1. 创建服务器端的Socket对象.
        ServerSocket server = new ServerSocket(12345);
        //2. 监听客户端连接.
        Socket accept = server.accept();
        //3. 创建字符高效流, 封装目的地文件.
        BufferedWriter bw = new BufferedWriter(new FileWriter("day14/data/2.txt"));
        //4. 通过Socket#getInputStream()获取输入流, 可以读取客户端写过来的数据,
        //为了写入方便, 将其封装成: 字符高效流.
        BufferedReader br = new BufferedReader(new InputStreamReader(accept.getInputStream()));
        //5. 定义变量, 记录读取到的数据.
        String line;
        //6. 循环读取, 只要条件满足, 就一直读, 并将读取到的内容赋值给变量line
        while ((line = br.readLine()) != null) {
            //7. 将读取到的内容写到目的地文件中.
            bw.write(line);
            bw.newLine();
            bw.flush();
        }
        //8. 释放资源.
        bw.close();
        accept.close();
    }
}
